<template>
  <basic-container>
    <div class="container-body">
      <el-form :inline="true" :model="query" class="demo-form-inline">
        <el-row>
          <el-form-item label="项目编号:" label-width="82px">
            <el-input v-model="query.projectCode" clearable placeholder="项目编号" size="small"></el-input>
          </el-form-item>
          <el-form-item label="项目名称:" label-width="82px">
            <el-input v-model="query.projectName" clearable placeholder="项目名称" size="small"></el-input>
          </el-form-item>
          <el-form-item label="项目进度:" label-width="82px">
            <el-select v-model="query.projectProgress" clearable filterable placeholder="项目进度">
              <el-option
                v-for="item in dict.type.project_progress"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="审计类型:" label-width="82px">
            <el-select v-model="query.auditType" clearable>
              <el-option v-for="dict in dict.type.audit_type" v-if="dict.value !== '0'" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年度:" label-width="82px">
            <el-select v-model="query.projectYear" clearable>
              <el-option v-for="planHeadYear in planHeadYears" :key="planHeadYear" :label="planHeadYear" :value="planHeadYear"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button :loading="loading" icon="el-icon-search" size="small" type="primary" @click="onSearch">搜索
            </el-button>
            <el-button :loading="loading" icon="el-icon-delete" size="small" @click="searchReset">清空</el-button>
          </el-form-item>
        </el-row>
      </el-form>
      <el-table v-loading="loading" :data="data" border
                header-row-class-name="container-table-header"
                row-key="id" size="small" stripe
                highlight-current-row @cell-click="handleCellClick"
                style="width: 100%;margin-bottom: 20px;">
        <el-table-column label="年度" prop="projectYear" width="80">
        </el-table-column>
        <el-table-column label="项目编号" prop="projectCode" width="125">
        </el-table-column>
        <el-table-column label="项目名称" prop="projectName">
        </el-table-column>
        <el-table-column label="审计类型" prop="effectiveDate">
          <template slot-scope="scope">
            <DictTag :options="dict.type.audit_type" :value="scope.row.auditType"></DictTag>
          </template>
        </el-table-column>
        <el-table-column label="立项日期" prop="projectDate">
        </el-table-column>
        <el-table-column label="通知书文号" prop="documentNumber" width="165">
        </el-table-column>
        <el-table-column label="项目进度" prop="projectProgress">
          <template slot-scope="scope">
            <DictTag :options="dict.type.project_progress" :value="scope.row.projectProgress"></DictTag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-row>
<!--              工作实施方案 查看-->
              <el-button v-if="permissions.prepare_apply_get && scope.row.applyStatus !== null"
                         icon="el-icon-view" size="small" type="text" class="custom-view-button"
                         @click="showViewBox(scope.row, 'ProjectApplyAuditView')">工作实施方案
              </el-button>
<!--              工作实施方案 编辑-->
<!--              <el-button v-if="permissions.prepare_apply_add && scope.row.applyStatus === 1"-->
<!--                         icon="el-icon-edit-outline" size="small" type="text"-->
<!--                         @click="addOrUpdateHandle(scope.row, 'applyForm')">工作实施方案-->
<!--              </el-button>-->

<!--              审计通知书 查看-->
              <el-button v-if="permissions.project_notice_get && scope.row.noticeStatus !== 1"
                         icon="el-icon-view" size="small" type="text" style="width: 75px; text-align: left;" class="custom-view-button"
                         @click="showViewBox(scope.row, 'ProjectNoticeAuditView')">审计通知书
              </el-button>
<!--              审计通知书 编辑-->
              <el-button v-if="permissions.project_notice_add && scope.row.noticeStatus === 1"
                         icon="el-icon-tickets" size="small" type="text" style="width: 75px; text-align: left;"
                         @click="addOrUpdateHandle(scope.row, 'noticeForm')">审计通知书
              </el-button>
            </el-row>
            <el-row>
<!--              人员变更-->
              <el-button v-if="permissions.project_personnel"
                         icon="el-icon-user" size="small" type="text" style="width: 90px; text-align: left;" class="custom-view-button"
                         @click="showGroupViewBox(scope.row)">人员变更
              </el-button>
<!--              项目台账 查看-->
              <el-button v-if="permissions.project_project_get"
                         icon="el-icon-document" size="small" type="text" style="width: 75px; text-align: left;"
                         @click="showViewBox(scope.row, 'ProjectAuditView')">项目台账
              </el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <div class="container-page">
        <el-pagination
          :current-page="page.current"
          :page-size="10"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="sizeChange"
          @current-change="currentChange">
        </el-pagination>
      </div>
    </div>

<!--    表格组件 查看-->
    <el-dialog top="5vh" :title="formTitle" :visible.sync="viewBox"
               :append-to-body="true" :before-close="closeViewBox" width="1200px">
      <component :is="auditView" :params="form" :management="isManagement"></component>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeViewBox" size="small" icon="el-icon-close">关闭</el-button>
      </span>
    </el-dialog>

<!--    表单组件 编辑-->
    <component @cancelDialog="cancelDialog" :is="auditEdit" :id="form.editProjectId"></component>

<!--    人员变更-->
    <el-dialog top="5vh" :title="formTitle" :visible.sync="viewGroupBox"
               :append-to-body="true" :before-close="closeGroupViewBox" width="1200px">
      <div style="display: flex; height: 200px;">
        <div class="colums_left">
          <div class="colums_left_middle">
            <div class="ledger">
              <div class="ledgerTitle">审计分工</div>
              <el-form ref="dataForm" :model="form" class="el-dialog__body" label-width="100px">
                <el-row>
                  <el-col :span="8">
                    <el-form-item label-width="140px" label="审计组组长:" prop="auditLeader" :rules="{required: true, message: '审计组组长不能为空', trigger: ['focus', 'change']}">
                      <el-input v-model="form.auditLeader" @focus="showTransferDialog(['auditLeaderId','auditLeader'], 'auditUser', false, form.assistCompanyId)" :readonly="true"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label-width="110px" label="协审单位组长:" prop="assistLeader" :rules="{required: true, message: '协审单位组长不能为空', trigger: ['focus', 'change']}">
                      <el-input v-model="form.assistLeader" @focus="showTransferDialog(['assistLeaderId','assistLeader'], 'user', false, form.assistCompanyId)" :readonly="true"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label-width="110px" label="协审单位主审:" prop="assistJudge" :rules="{required: true, message: '协审单位主审不能为空', trigger: ['focus', 'change']}">
                      <el-input v-model="form.assistJudge" @focus="showTransferDialog(['assistJudgeId','assistJudge'], 'user', false, form.assistCompanyId)" :readonly="true"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="8">
                    <el-form-item label-width="140px" label="被审计单位联络员:" prop="auditedCompanyUserName" :rules="{required: true, message: '被审计单位联络员不能为空', trigger: ['focus', 'change']}">
                      <el-input v-model="form.auditedCompanyUserName" @focus="showTransferDialog(['auditedCompanyUserId','auditedCompanyUserName'], 'auditedUser', true, form.auditedCompanyId)" :readonly="true"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="16">
                    <el-form-item label-width="110px" label="审计组成员:" prop="assistMembers" :rules="{required: true, message: '审计组成员不能为空', trigger: ['focus', 'change']}">
                      <el-input v-model="form.assistMembers" @focus="showTransferDialog(['assistMemberIds','assistMembers'], 'user', true, form.assistCompanyId)" :readonly="true"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-check" size="small" type="primary" @click="updateGroup">保存</el-button>
        <el-button icon="el-icon-close" size="small" @click="closeGroupViewBox">关闭</el-button>
      </span>
    </el-dialog>
    <FormTransfer :transferDialog="transferDialog" :transferDialogType="transferDialogType" :multiple="transferDialogMultiple" :transferCurrent="transferCurrent" @transferData="transferDataHandle" @closeTransfer="closeTransfer"/>
  </basic-container>
</template>

<script>
import {mapGetters} from "vuex";
import FormTransfer from "@/components/form/transfer";
import {listPlanHeadYear} from "@/api/adis/work/plan";
import {fetchProjectList, getProject, projectSubmit} from "@/api/adis/project/project";
import {getApplyByProjectId} from "@/api/adis/project/projectApply";
import {getNoticeByProjectId} from "@/api/adis/project/notice";

export default {
  components: {
    FormTransfer,
  },
  dictTypes: ['audit_type', 'project_progress'],
  data() {
    return {
      ls: {
        'background': 'white'
      },
      importBox: false,
      isEdit: false,
      isView: false,
      isManagement: true,
      viewBox: false,
      viewGroupBox: false,
      formBox: false,
      formTitle: '',
      loading: false,
      showStartDate: false,
      // 控制实施时间输入框的显示与否
      showEndDate: false,
      multiple: false,
      transferDialog: false,
      transferDialogType: '',
      transferDialogTypeArr: [],
      transferDialogMultiple: false,
      transferCurrent: {},
      selectedRowsId: '',
      addOrUpdateNoticeVisible: false,
      addOrUpdateApplyVisible: false,
      addOrUpdateEngineeringNoticeVisible: false,
      addOrUpdateEngineeringApplyVisible: false,
      query: {},
      form: {},
      planHeadYears: [],
      page: {
        size: 10,
        current: 1,
        total: 0
      },
      data: [],
      Authorization: '',
      auditView: '',
      auditEdit: '',
      fileList: [], // 文件
    }
  },
  computed: {
    ...mapGetters(["permissions", "userInfo"])
  },
  created() {
    this.onLoad(this.page);
    this.Authorization = 'Bearer ' + this.$store.getters.access_token
  },
  methods: {
    // 获取所有已经审批通过的年度计划年度
    listPlanHeadYear(){
      listPlanHeadYear().then((res) => {
        this.$set(this,"planHeadYears", res.data.data)
      });
    },

    handleCellClick(row, column) {
      if (row && column.label !== "操作"){
        this.showViewBox(row, "ProjectAuditView")
      }
    },

    // 页面表单相关
    addOrUpdateHandle(row, view){
      this.auditEdit = view
      this.form.editProjectId = row.projectId
    },
    cancelDialog() {
      this.form.editProjectId = ''
      this.onLoad(this.page)
      setTimeout(() => {
        this.auditEdit = null
      }, 500)
    },

    //  控制实施时间输入框的显示方法
    toggleDateConditions() {
      this.showStartDate = !this.showStartDate;
      this.showEndDate = !this.showEndDate;
    },
    onSearch() {
      this.page.current = 1;
      this.onLoad(this.page);
    },
    searchReset() {
      this.query = {};
      this.page.current = 1;
      this.onLoad(this.page);
    },
    currentChange(current) {
      this.page.current = current;
      this.onLoad(this.page);
    },
    sizeChange(size) {
      this.page.size = size;
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      this.query.isEngineering = false;
      this.query.isTermination = false;
      this.query.auditStatus = 3;
      fetchProjectList(Object.assign(params, this.query, page)).then(res => {
        this.loading = false;
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.data.forEach(record => {
          record.documentNumber = '浙工大审通（'+ record.noticeYear +'）'+ record.noticeCode +'号';
        });
        this.listPlanHeadYear()
      }, () => {
        this.loading = false;
      });
    },

    fetchResourceByView(view, projectId) {
      switch (view) {
        case 'ProjectAuditView':
          return getProject(projectId).then(response => response.data.data);
        case 'ProjectApplyAuditView':
          return getApplyByProjectId(projectId).then(response => response.data.data);
        case 'ProjectNoticeAuditView':
          return getNoticeByProjectId(projectId).then(response => response.data.data);
      }
      return Promise.reject(new Error('Invalid view'));
    },
    showViewBox(row, view) {
      this.auditView = view;
      this.fetchResourceByView(view, row.projectId).then(data => {
          data.activeName = "project"
          this.form = data;
          this.formTitle = row.projectName;
          this.viewBox = true;
      });
    },
    closeViewBox() {
      this.viewBox = false;
    },

    showGroupViewBox(row) {
      this.form = row
      this.formTitle = row.projectName
      this.viewGroupBox = true;
    },
    closeGroupViewBox() {
      this.viewGroupBox = false;
      this.onLoad(this.page);
    },

    updateGroup() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          projectSubmit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.closeGroupViewBox();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },

    showTransferDialog(transferDialogArr, transferDialogType, transferDialogMultiple, transferDialogQuery) {
      this.transferDialogArr = transferDialogArr; // 表单字段
      this.transferDialogType = transferDialogType; // 判断类型user:人员，unit:职位，department:部门,company:单位,plan:计划等
      this.transferDialogMultiple = transferDialogMultiple; // 是否多选
      if (transferDialogType === 'company') {
        this.transferCurrent.type = transferDialogQuery;
      }
      if (transferDialogType === 'user') {
        if(!transferDialogQuery) {
          this.$message({
            type: "warning",
            message: "请先选择单位!"
          });
          return
        }
        this.transferCurrent.deptId = transferDialogQuery;
      }
      //重组数组name和id
      this.transferCurrent.currentval = []
      if(this.form[transferDialogArr[0]]) {
        if (this.form[transferDialogArr[0]].indexOf(',') > -1) {
          this.form[transferDialogArr[0]].split(',').forEach((item, i) => {
            this.transferCurrent.currentval.push({name: this.form[transferDialogArr[1]].split(',')[i], id: item})
          })
        } else {
          this.transferCurrent.currentval = [{name: this.form[transferDialogArr[1]], id: this.form[transferDialogArr[0]]}]
        }
      }
      this.transferDialog = true;
    },
    closeTransfer() {
      this.transferDialog = false
      this.transferDialogType = ''
    },
    // 已选定数据的更新判断
    transferDataHandle(e) {
      this.transferDialog = false
      let currentval = [], currentLabel = []
      if (e.list.length > 0) {
        if (e.list.length > 1) {
          e.list.forEach(item => {
            currentval.push(item.id)
            currentLabel.push(item.name)
          })
        } else {
          currentval = [e.list[0].id]
          currentLabel = [e.list[0].name]
        }
        this.$set(this.form, this.transferDialogArr[0], currentval.join(','))
        this.$set(this.form, this.transferDialogArr[1], currentLabel.join(','))
      } else { // 如果返回的数据为空，也将当前页面数值清空
        this.$set(this.form, this.transferDialogArr[0], '')
        this.$set(this.form, this.transferDialogArr[1], '')
      }
      console.log(this.form, 'this.form')
      this.transferDialogType = ''
    },

    downWord() {
      if(!this.form.wordFile) {
        this.$message({
          type: "warning",
          message: "该项尚未上传相关文书!"
        });
        return;
      }
      const a = document.createElement('a');
      let url = this.form.wordFile;
      a.setAttribute('download', '');
      a.setAttribute('href', url);
      a.click();
    },
    openWord() {
      if(!this.form.wordFile) {
        this.$message({
          type: "warning",
          message: "该项尚未上传相关文书!"
        });
        return;
      }
      // this.$router.push({path:'/webOffice', query: {url: this.form.wordFile}})
      const { href } = this.$router.resolve({
        path: '/webOffice',
        query: {
          url: this.form.wordFile,
          type: this.isAudit ? 'edit' : 'view',
        }
      });
      window.open(href, '_blank');
    }
  }
};
</script>

<style>
.custom-view-button {
  color: #36ba70;
}

.custom-view-button:hover {
  color: #59d592;
}
</style>
